﻿'20130520
'檔案比對
Imports System.IO
Imports EqMonitor.Utilities.FTP
Module CompareFile
    Sub New()

    End Sub
    
    Function Compare(ByVal file1 As String, ByVal file2 As String) As Boolean
        Dim fs1 As FileStream = File.OpenRead(file1)
        Dim fs2 As FileStream = File.OpenRead(file2)
        '1.檢查文件大小
        If Not (fs1.Length = fs2.Length) Then
            fs1.Dispose()
            fs2.Dispose()
            GC.Collect()
            Return False
        End If
        '2.比對內容，逐一找出每一字元，法一
        Dim filebyte1 As Integer = 0
        Dim filebyte2 As Integer = 0
        Do
            filebyte1 = fs1.ReadByte
            filebyte2 = fs2.ReadByte
        Loop While ((filebyte1 = filebyte2) And ((Not filebyte1 = -1) Or (Not filebyte2 = -1)))
        If (filebyte1 - filebyte2) = 0 Then
            'Return true 
        Else
            fs1.Dispose()
            fs2.Dispose()
            GC.Collect()
            Return False
        End If

        '3.比對內容，逐一找出每一字元，法二
        Dim byte1() As Byte = File.ReadAllBytes(file1)
        Dim byte2() As Byte = File.ReadAllBytes(file2)
        Dim i As Integer = 0
        Do
            If Not byte1(i) = byte2(i) Then
                fs1.Dispose()
                fs2.Dispose()
                GC.Collect()
                Return False
            End If
            i = i + 1
        Loop While (i < byte1.Length)
        Return True
    End Function
    Public Function FtpAndLocal_Compare(ByVal Ftpip As String, ByVal Account As String, ByVal Password As String, ByVal ftp_file As String, ByVal Local_file As String) As Boolean
        Try
            Dim FtpClient As New FTPclient(Ftpip, Account, Password)
            If Not Directory.Exists(Directory.GetCurrentDirectory + "\temp\") Then
                Directory.CreateDirectory(Directory.GetCurrentDirectory + "\temp\")

                Console.WriteLine(Directory.GetCurrentDirectory + "\temp\")
            End If
            If Not Directory.Exists(Directory.GetCurrentDirectory + "\temp\c_file\") Then
                Directory.CreateDirectory(Directory.GetCurrentDirectory + "\temp\c_file\")
            End If

            Dim newfileParh As String = Directory.GetCurrentDirectory + "\temp\c_file\" + Ftpip + "_" + Now.Second.ToString + Now.Millisecond.ToString
            While File.Exists(newfileParh)
                newfileParh = Directory.GetCurrentDirectory + "\temp\c_file\" + Ftpip + "_" + Now.Second.ToString + Now.Millisecond.ToString
            End While
            FtpClient.Download(ftp_file, newfileParh, True)
            Return CompareFile.Compare(newfileParh, Local_file)
        Catch ex As Exception
            Throw ex
            'Throw New Exception(ex.Message)
            Return False
        End Try

    End Function
End Module
